# 模型生成


# mysql 数据模型
import cache


class MysqlModel:
    def __init__(self, args):
        self.args = args
        self.msg = None
        self.dbConfig = {}
        self._create()
        self.dbCacheObject = None

    # 创建数据库模型
    def _create(self):
        args = self.args
        host = args['host'] if 'host' in args else 'localhost'
        user = args['user'] if 'user' in args else 'root'

        password = args['pswd'] if 'pswd' in args else None
        dbname = args['dbname'] if 'dbname' in args else None
        charset = args['charset'] if 'charset' in args else 'utf8'

        if not password or password == '':
            self.msg = 'pswd 库密码不存在'
            return
        if not dbname or dbname == '':
            self.msg = 'dbname 库密码不存在'
            return

        self.dbConfig = {
            'host': host,
            'user': user,
            'password': password,
            'db': dbname,
            'charset': charset
        }
        if 'name' in args and args['name']:
            self.dbConfig['name'] = args['name']

        # 数据库缓存
        dbCache = cache.DatabaseCache(self.dbConfig)
        dbCache.cache_conn_ini()
        dbCache.cache_struct()
        self.dbCacheObject = dbCache

    @staticmethod
    def create_by_name(name: str):
        """
        通过名称读取项目
        :param name:str
        :return:
        """
        dbCache = cache.DatabaseCache(name)
        success, msg = dbCache.is_success()
        if not success:
            return msg

        dbCache.cache_conn_ini()
        dbCache.cache_struct()
        return None
